package com.example.nettydemo.codec.marshalling;

import com.example.nettydemo.codec.ptotobuf.SubscibeReqProto;
import com.example.nettydemo.codec.ptotobuf.SubscibeRespProto;
import com.google.protobuf.TextFormat;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class MarshallingSubReqClientHandler extends ChannelHandlerAdapter {

    private int counter;

    public MarshallingSubReqClientHandler(){

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i = 0; i < 1000; i++){

            SubscibeReq subscibeReq = createSubscibeReq(i);
            log.info("请求参数: [{}]", subscibeReq.toString());
            ctx.write(subscibeReq);
        }
        ctx.flush();
    }

    private SubscibeReq createSubscibeReq(int i){
        SubscibeReq req = new SubscibeReq();
        req.setSubReqID(Long.valueOf(i));
        req.setUserName("name1");
        req.setProductName("book1");

        List<String> address =  new ArrayList<>();
        address.add("地址1");
        address.add("地址2");
        req.setAddress(address);

        return req;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("客户端, 错误信息", cause);
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscibeResp subscibeResp = (SubscibeResp) msg;
        log.info("response: [{}], desc: [{}], counter: [{}]", subscibeResp, subscibeResp.getDesc(), ++counter);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
